<template>
  <div class="sync-task-table">
    <div class="table-header">
      <a-space>
        <a-input
          v-model:value="filters.task_name"
          placeholder="任务名称"
          style="width: 200px"
          allowClear
          @pressEnter="handleFilterChange"
        />
        <a-select
          v-model:value="filters.sync_status"
          placeholder="同步状态"
          style="width: 150px"
          allowClear
          @change="handleFilterChange"
        >
          <a-select-option value="pending">等待中</a-select-option>
          <a-select-option value="running">运行中</a-select-option>
          <a-select-option value="success">成功</a-select-option>
          <a-select-option value="failed">失败</a-select-option>
        </a-select>
        <a-select
          v-model:value="filters.sync_mode"
          placeholder="同步模式"
          style="width: 150px"
          allowClear
          @change="handleFilterChange"
        >
          <a-select-option value="manual">手动</a-select-option>
          <a-select-option value="scheduled">定时</a-select-option>
        </a-select>
        <a-button type="primary" @click="loadSyncTasks">
          <template #icon><SearchOutlined /></template>
          查询
        </a-button>
        <a-button
          @click="handleBatchExecute"
          :disabled="selectedRowKeys.length === 0"
          type="default"
        >
          <template #icon><PlayCircleOutlined /></template>
          批量执行 ({{ selectedRowKeys.length }})
        </a-button>
      </a-space>
    </div>

    <a-table
      :columns="tableColumns"
      :data-source="syncTasks"
      :loading="loading"
      :pagination="pagination"
      :row-selection="rowSelection"
      row-key="id"
      @change="handlePaginationChange"
      :scroll="{ x: 1400 }"
      :row-class-name="getRowClassName"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'sync_status'">
          <a-badge
            :status="getStatusBadge(record.sync_status)"
            :text="getStatusText(record.sync_status)"
          />
        </template>
        <template v-if="column.key === 'sync_mode'">
          <a-tag :color="record.sync_mode === 'scheduled' ? 'blue' : 'default'">
            {{ record.sync_mode === 'scheduled' ? '定时' : '手动' }}
          </a-tag>
        </template>
        <template v-if="column.key === 'progress'">
          <a-progress
            :percent="getProgressPercent(record)"
            :status="getProgressStatus(record)"
            size="small"
            :stroke-color="getProgressColor(record)"
          />
          <div class="progress-info" v-if="record.total_records > 0">
            <span class="progress-text">
              {{ record.synced_records }} / {{ record.total_records }}
            </span>
            <span class="progress-error" v-if="record.failed_records > 0">
              (失败: {{ record.failed_records }})
            </span>
          </div>
        </template>
        <template v-if="column.key === 'last_sync_time'">
          <div>
            <div>{{ formatDateTime(record.last_sync_time) }}</div>
            <div class="next-sync-time" v-if="record.next_sync_time && record.is_active">
              下次: {{ formatDateTime(record.next_sync_time) }}
            </div>
          </div>
        </template>
        <template v-if="column.key === 'actions'">
          <a-space>
            <a-button
              size="small"
              type="primary"
              :disabled="record.sync_status === 'running'"
              @click="handleExecuteTask(record)"
              :loading="record.executing"
            >
              <template #icon><PlayCircleOutlined /></template>
              执行
            </a-button>
            <a-button size="small" @click="handleViewTaskDetail(record)">
              详情
            </a-button>
            <a-button size="small" @click="handleViewLogs(record)">
              日志
            </a-button>
            <a-dropdown>
              <template #overlay>
                <a-menu>
                  <a-menu-item @click="handleEditTask(record)">
                    编辑
                  </a-menu-item>
                  <a-menu-item @click="handleToggleTask(record)">
                    {{ record.is_active ? '禁用' : '启用' }}
                  </a-menu-item>
                  <a-menu-item @click="handleDeleteTask(record)" danger>
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button size="small">
                更多 <DownOutlined />
              </a-button>
            </a-dropdown>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { SearchOutlined, DownOutlined, PlayCircleOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { useSyncUtils } from '@/composables/useSyncData'

const props = defineProps({
  syncTasks: {
    type: Array,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  },
  pagination: {
    type: Object,
    required: true
  },
  filters: {
    type: Object,
    required: true
  },
  selectedRowKeys: {
    type: Array,
    required: true
  },
  rowSelection: {
    type: Object,
    required: true
  }
})

const emit = defineEmits([
  'load-sync-tasks',
  'execute-task',
  'batch-execute-tasks',
  'view-task-detail',
  'view-logs',
  'edit-task',
  'toggle-task',
  'delete-task',
  'pagination-change',
  'filter-change'
])

const {
  formatDateTime,
  getStatusBadge,
  getStatusText,
  getProgressPercent,
  getProgressStatus
} = useSyncUtils()

// 优化的表格列配置
const tableColumns = computed(() => [
  {
    title: '任务名称',
    dataIndex: 'task_name',
    key: 'task_name',
    width: 200,
    fixed: 'left',
    ellipsis: true
  },
  {
    title: '数据源',
    dataIndex: ['data_source', 'name'],
    key: 'data_source',
    width: 150,
    ellipsis: true
  },
  {
    title: '源表',
    dataIndex: 'source_table',
    key: 'source_table',
    width: 120,
    ellipsis: true
  },
  {
    title: '同步模式',
    dataIndex: 'sync_mode',
    key: 'sync_mode',
    width: 100,
    filters: [
      { text: '手动', value: 'manual' },
      { text: '定时', value: 'scheduled' }
    ]
  },
  {
    title: '同步状态',
    dataIndex: 'sync_status',
    key: 'sync_status',
    width: 100,
    filters: [
      { text: '等待中', value: 'pending' },
      { text: '运行中', value: 'running' },
      { text: '成功', value: 'success' },
      { text: '失败', value: 'failed' }
    ]
  },
  {
    title: '进度',
    key: 'progress',
    width: 200
  },
  {
    title: '最后同步时间',
    dataIndex: 'last_sync_time',
    key: 'last_sync_time',
    width: 160,
    sorter: true
  },
  {
    title: '操作',
    key: 'actions',
    width: 280,
    fixed: 'right'
  }
])

// 获取进度条颜色
const getProgressColor = (task) => {
  if (task.sync_status === 'failed') return '#ff4d4f'
  if (task.sync_status === 'success') return '#52c41a'
  if (task.sync_status === 'running') return '#1890ff'
  return '#d9d9d9'
}

// 获取行类名，用于状态视觉区分
const getRowClassName = (record) => {
  if (record.sync_status === 'running') return 'table-row-running'
  if (record.sync_status === 'failed') return 'table-row-failed'
  if (record.sync_status === 'success') return 'table-row-success'
  return ''
}

// 事件处理函数
const loadSyncTasks = () => emit('load-sync-tasks')

const handleExecuteTask = (task) => emit('execute-task', task)

const handleBatchExecute = () => emit('batch-execute-tasks', props.selectedRowKeys)

const handleViewTaskDetail = (task) => emit('view-task-detail', task)

const handleViewLogs = (task) => emit('view-logs', task)

const handleEditTask = (task) => emit('edit-task', task)

const handleToggleTask = (task) => emit('toggle-task', task)

const handleDeleteTask = (task) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除同步任务"${task.task_name}"吗？此操作不可恢复。`,
    okText: '确认',
    cancelText: '取消',
    onOk: () => emit('delete-task', task.id)
  })
}

const handlePaginationChange = (pagination, filters, sorter) => {
  emit('pagination-change', pagination)
}

const handleFilterChange = () => emit('filter-change')
</script>

<style scoped>
.sync-task-table {
  background: white;
  border-radius: 8px;
  padding: 16px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.progress-info {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.progress-text {
  margin-right: 8px;
}

.progress-error {
  color: #ff4d4f;
}

.next-sync-time {
  font-size: 12px;
  color: #1890ff;
  margin-top: 2px;
}

:deep(.ant-table-tbody > tr.ant-table-row:hover > td) {
  background: #f5f5f5;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}

:deep(.table-row-running > td) {
  background-color: #e6f7ff;
}

:deep(.table-row-failed > td) {
  background-color: #fff2f0;
}

:deep(.table-row-success > td) {
  background-color: #f6ffed;
}

:deep(.ant-btn-sm) {
  font-size: 12px;
}

:deep(.ant-progress-text) {
  font-size: 12px;
}

:deep(.ant-dropdown-trigger) {
  display: flex;
  align-items: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .table-header {
    flex-direction: column;
    align-items: stretch;
  }

  .table-header .ant-space {
    width: 100%;
    flex-wrap: wrap;
  }
}
</style>